package com.szbmyoubao.app.ui.login

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.constraintlayout.widget.ConstraintLayout
import com.ellecity06.common.R
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.databinding.ActivityVerificationCodeBinding
import org.json.JSONException
import org.json.JSONObject

/**
 * @author ellecity06
 * @time 2025/3/17 14:33
 * @des
 */
class VerificationCodeActivity : BaseMvvmActivity<ActivityVerificationCodeBinding, BaseViewModel>() {

    companion object {
        fun launch(activity: Activity, code: Int) {
            activity.startActivityForResult(Intent(activity, VerificationCodeActivity::class.java), code)
            activity.overridePendingTransition(R.anim.activity_bottom_in, 0)
        }
    }

    override fun finish() {
        super.finish()
        this.overridePendingTransition(R.anim.activity_top_out, 0);
    }

    override val userBaseTitle: Boolean
        get() = false

    override fun inflateBinding(): ActivityVerificationCodeBinding {
        return ActivityVerificationCodeBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetJavaScriptEnabled", "ClickableViewAccessibility")
    override fun initialize(savedInstanceState: Bundle?) {
        val webSettings: WebSettings = binding.webview.settings
        webSettings.domStorageEnabled = true
        webSettings.javaScriptEnabled = true
        webSettings.blockNetworkImage = false
        // 可选，设置开启Chrome调试
        WebView.setWebContentsDebuggingEnabled(true);
        // 设置屏幕自适应。
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        binding.webview.overScrollMode = View.OVER_SCROLL_NEVER
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        // 建立JavaScript调用Java接口的桥梁。
        binding.webview.addJavascriptInterface(TestJsInterface(this), "testInterface")
        binding.webview.setOnTouchListener(object : OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                // 返回false表示取消原生的滑动
                return false
            }
        })
        val params = binding.webview.layoutParams as ConstraintLayout.LayoutParams

        params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
        params.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
        params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
        params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID

        binding.grayBackground.visibility = View.VISIBLE


        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenWidth = displayMetrics.widthPixels

        params.width = (screenWidth * 0.9).toInt()
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
        binding.webview.layoutParams = params
//        binding.webview.setWebContentsDebuggingEnabled(true)
        binding.webview.webViewClient = object : WebViewClient() {
            public override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }
        binding.webview.loadUrl("file:///android_asset/index.html")
    }

    /** 实例化接口并传入上下文  */
    inner class TestJsInterface internal constructor(var mActivity: Activity) {
        @JavascriptInterface
        @Throws(JSONException::class)
        fun getVerifyResult(jsonString: String) {
            logD("jsonString=${jsonString}")
            try {
                // 将JSON字符串转换为JSONObject
                val jsonObject = JSONObject(jsonString)
                val captchaVerifyParam = jsonObject.getString("data")
                val callbackName = jsonObject.getString("callback")
                setResult(RESULT_OK, Intent().apply {
                    putExtra("verifyMsg", captchaVerifyParam)
                })
                finish()
                // 用captchaVerifyParam请求后端接口拿到请求结果
                // JSONObject verifyResult = requestAPI(captchaVerifyParam);
//                val result = JSONObject()
//                // 这里模拟一下返回结果
//                result.put("captchaResult", true)
//                result.put("bizResult", true)
//
//                val resultString = result.toString() // result可以转换为一个JSON字符串，注意传给H5之后的数据格式转换
//                println(resultString)
//
//                // 处理完数据后，将结果回传给H5页面
//                // 这里需要确保操作在主线程(UI线程)中执行
//                binding.webview.post(object : Runnable {
//                    override fun run() {
//                        // 使用evaluateJavascript发送回调到H5页面
//                        binding.webview.evaluateJavascript("javascript:" + callbackName + "('" + escapeJavaScriptString(resultString) + "')", null)
//                        // 根据result在App测来执行业务自定义提示逻辑，H5中的onBizResultCallback可以置为空函数
//                    }
//                })
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        @JavascriptInterface
        fun closeWebView() {
            mActivity.runOnUiThread(object : Runnable {
                override fun run() {
                    mActivity.finish() // 如果WebView是在单独的Activity中，直接关闭Activity
                    // 如果WebView不在单独的Activity中，可以这样隐藏或移除WebView
                    // webView.setVisibility(View.GONE); // 或 webView.getParent().removeView(webView);
                }
            })
        }
    }

    // 对JavaScript字符串进行转义，避免JavaScript注入问题
    private fun escapeJavaScriptString(string: String): String {
        // 这是一个简单的转义示例。对于更复杂的情况，可能需要更有效的转义方法
        return string.replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"")
    }

}